﻿namespace WebPacker.Logger
{
	using System;
	using System.Threading;

	public static class LogFactory
	{
		private static readonly LoggerWrapper instance = new LoggerWrapper();

		public static ILogger GetLogger()
		{
			return instance;
		}

		public static void SetLogger(ILogger logger)
		{
			instance.SetBaseLogger(logger);
		}

		/// <summary>
		/// Wrapper for permanent reference on actual logger.
		/// </summary>
		private class LoggerWrapper : ILogger
		{
			private ILogger logger;

			public LoggerWrapper()
			{
				SetBaseLogger(null);
			}

			public bool Enabled
			{
				get { return logger.Enabled; }
				set { logger.Enabled = value; }
			}

			public void SetBaseLogger(ILogger baseLogger)
			{
				if (baseLogger == null)
				{
					baseLogger = new NullLogger();
				}

				Interlocked.Exchange(ref logger, baseLogger);
			}

			public void Log(LogLevel logLevel, LogMessageBuilder messageBuilder)
			{
				logger.Log(logLevel, messageBuilder);
			}

			public void LogException(LogLevel logLevel, LogMessageBuilder messageBuilder, Exception exception)
			{
				logger.LogException(logLevel, messageBuilder, exception);
			}
		}
	}
}